<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>百度地图</title>
    <style>
      #allmap {
        width: 10px;
        height: 10px;
      }
    </style>
    <script src="https://api.map.baidu.com/api?v=2.0&ak=AzzspeXAaeNiDFnzWqVlsFGyuC7uF1gq"></script>
  </head>
  <body>
    <button onclick="getLocation()">IP定位</button>
    <button onclick="getGeolocation()">浏览器定位</button>

    <script>
      const getAddress = (point, type = 'geo') => {
        return new Promise(resolve => {
          var geoc = new BMap.Geocoder();
          geoc.getLocation(point, function (rs) {
            if (type === 'geo') {
              resolve(rs.addressComponents)
            } else {
              resolve({ ...rs.addressComponents, district: '', street: '', streetNumber: ''})
            }
          });
        })
      };

      const getLocation = () => {
        var myCity = new BMap.LocalCity();

        myCity.get(async (r) => {
          const data = await getAddress(new BMap.Point(r.center.lng, r.center.lat), 'city')
          console.log("城市信息", data);
        });
      };

      const getGeolocation = () => {
        var geolocation = new BMap.Geolocation();
        // 开启SDK辅助定位
        geolocation.enableSDKLocation();
        geolocation.getCurrentPosition(async (r) => {
          const data = await getAddress(new BMap.Point(r.longitude, r.latitude))
          console.log("城市信息", data);
        });
      };
    </script>
  </body>
</html>
